package pw.orm.core;

import java.sql.*;

/**
 * @Author Eric
 * @Desc
 * @Date Create in 17-12-29 下午5:18
 * @Modified By
 */
public class JormSession {

    private Connection connection = null;

    private JormSession(Connection connection){
        this.connection = connection ;
    }


    public void startTransaction() throws SQLException{
        connection.setAutoCommit(false);
    }

    public void commit() throws SQLException{
        connection.commit();
    }

    public int update(String sql ,Object [] params) throws SQLException{
        PreparedStatement preparedStatement = prepareStatement(sql,params);
        return preparedStatement.executeUpdate();
    }

    public Object saveBindId(String sql ,Object [] params) throws SQLException{
        PreparedStatement preparedStatement = prepareStatement(sql,params);
        preparedStatement.executeUpdate();
        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            return resultSet.getObject(1);
        }else {
            return null;
        }
    }

    public ResultSet select(String sql ,Object [] params) throws SQLException{
        PreparedStatement preparedStatement = prepareStatement(sql,params);
        return preparedStatement.executeQuery();
    }

    private PreparedStatement prepareStatement(String sql ,Object [] params) throws SQLException {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
        } catch (SQLFeatureNotSupportedException e) {
            try {
                preparedStatement = connection.prepareStatement(sql);
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw e1;
            }
        }

        if(params == null || params.length ==0) return preparedStatement;

        for(int i=0;i<params.length;i++){
            preparedStatement.setObject(i+1, params[i]);
        }
        return preparedStatement;
    }

    public static JormSession create(Connection connection){
        return new JormSession(connection);
    }
}
